let get_dims img =
  ((Sdlvideo.surface_info img).Sdlvideo.w, (Sdlvideo.surface_info
                                              img).Sdlvideo.h)

let rec check2 color = function
[] -> false
  | (c,v)::l when c = color -> true
  | (c,v)::l -> check2 color l ;;

let rec upColor color = function
[] -> []
  | (c,v)::l when c = color -> (c,(v+1))::(upColor color l)
  | (c,v)::l -> (c,v)::(upColor color l)

let getValue listColor =
  let value = ref 1 in
  let rec getValue2 listColor =
    match listColor with
        [] -> !value
      | (c,v)::l when v > !value -> value := v ;
                                    getValue2 l
      | (c,v)::l -> getValue2 l in
  getValue2 listColor

let rec getColor value = function
[] -> invalid_arg "getColor : Liste vide"
  | (c,v)::l when v = value -> c
  | (c,v)::l -> getColor value l

let antibruit exImg brImg i h param =
  let get_width (w, h) = w in
  let get_height (w, h) = h in
  let listeCouleurs = ref [] in
  if ((i <= param) || (h <= param) || (i >= ((get_width (get_dims exImg))
	- param)) || (h >= (get_height (get_dims exImg) - param))) then
    Sdlvideo.put_pixel_color brImg i h (Sdlvideo.get_pixel_color exImg i h)
  else
    begin
      for a = i - param to i + param do
	for b = h - param to h + param do
          let color = (Sdlvideo.get_pixel_color exImg a b) in
	  if check2 color !listeCouleurs then
            listeCouleurs := upColor color !listeCouleurs
	  else
            listeCouleurs := ((color,1)::(!listeCouleurs)) ;
	done
      done ;
      let finalList = !listeCouleurs in
      Sdlvideo.put_pixel_color brImg i h ((getColor (getValue finalList)
					     finalList)) ;
    end
        
let main exImg brImg param =
  let get_width (w, h) = w in
  let get_height (w, h) = h in
  for h = 0 to (get_height (get_dims exImg) - 1) do
    for i = 0 to (get_width (get_dims exImg)) do
      antibruit exImg brImg h i param ;
    done
  done
